package com.duvee.uiautomator.interfaces;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
import com.duvee.uiautomator.bean.PhoneInfoBean;
import com.duvee.uiautomator.bean.TestCaseBean;
import com.duvee.uiautomator.common.Constants;
import com.duvee.uiautomator.common.GsonUtil;
import com.duvee.uiautomator.interfaceImp.AuxiliaryInterfacefaceImp;
import com.duvee.uiautomator.thread.GetPost;

/**
 * 测试基类
 * 
 * @author duvee
 * 
 */
public abstract class BaseTestCase extends UiAutomatorTestCase implements
		TestCaseInterface {
	public List<String> caseList = new ArrayList<String>();// 测试用例列表
	public AuxiliaryInterfacefaceImp auxiliary = new AuxiliaryInterfacefaceImp();// 辅助类
	public UiDevice device; // 设备
	public PhoneInfoBean phoneInfo = new PhoneInfoBean(); // 测试用例bean
	String url = "http://120.194.28.114:8082/lbt-ls-server/club/cdynamiccomment/getPhoneInfo.do?";
	// 后台服务地址
	String imagePath = "/storage/sdcard0/UIAutomatorInfo/"; // 默认文件存放路径
	Date current = new Date();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
	public String c = sdf.format(current); // 日期格式化
	File file; // 测试用例文件
	public List<TestCaseBean> list = new ArrayList<TestCaseBean>(); // 存放测试用例list
	public String result = "通过";
	public AuxiliaryInterfacefaceImp au = new AuxiliaryInterfacefaceImp();
	public String phoneModel, phoneRelease;// 手机型号、手机系统版本号
	public UiObject obj; // 为子类提供对象

	/**
	 * 任务执行顺序 获取设备信息--启动APP--测试用例--动作
	 */
	@Override
	public void testCase() {
		device = getUiDevice();
		phoneModel = android.os.Build.MODEL;
		phoneRelease = android.os.Build.VERSION.RELEASE;
		caseInfo();
		event();
	}

	public boolean startApp(String activityName) {
		// 启动APP
		try {
			Runtime.getRuntime().exec("am start -n " + activityName);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	};

	/**
	 * 根据设备名获取对应ID
	 */
	public PhoneInfoBean getProductInfo(String productName) {
		String responseURL = GetPost.sendPost(url, "phonemodel=" + productName);
		phoneInfo = GsonUtil.getInstance(null).fromJson(responseURL,
				PhoneInfoBean.class);
		return phoneInfo;
	};

	/**
	 * 根据不同ID、text等获取对象
	 * 
	 * @param id
	 * @return
	 */
	public UiObject getObjectByID(String id) {
		UiObject obj = new UiObject(new UiSelector().resourceId(id));
		return obj;
	}

	public UiObject getObjectByText(String text) {
		UiObject obj = new UiObject(new UiSelector().text(text));
		return obj;
	}

	public UiObject getObjectByIDAndText(String text, String id) {
		UiObject obj = new UiObject(new UiSelector().text(text).resourceId(id));
		return obj;
	}

	/**
	 * 截图功能，传入应用名称
	 * 
	 * @param path
	 */
	public void takeScreenShot(String path) {
		getUiDevice().takeScreenshot(new File(imagePath + c + "_" + path), 0,
				50);
		sleep(2000);
	}

	/**
	 * 检查文件是否存在
	 * 
	 * @param fileName
	 *            文件名
	 * @throws IOException
	 * @throws BiffException
	 * @throws RowsExceededException
	 * @throws WriteException
	 */
	public void checkFile(String fileName) throws IOException, BiffException,
			RowsExceededException, WriteException {
		/*
		 * 该方法检查文件是否存在，如果存在返回该文件，如果不存在创建该文件并返回
		 */
		file = new File(fileName);

		WritableWorkbook workbook = null;
		// 判断文件是否存在
		if (file.exists() && file.isFile()) {
			workbook = Workbook.createWorkbook(file);
		}
		// 创建新文件
		else {
			file.createNewFile();
			workbook = Workbook.createWorkbook(file);// 找到这个文件
			WritableSheet ws = workbook.createSheet("sheet1", 0);// 创建sheet
			// 设置格式
			ws.getSettings().setDefaultColumnWidth(20); // 设置列的宽度
			// 设置字体
			WritableFont wf = new WritableFont(WritableFont.ARIAL, 14,
					WritableFont.BOLD, false);
			WritableCellFormat wcfF = new WritableCellFormat(wf);
			try {
				wcfF.setWrap(true);// 自动换行
				wcfF.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 把垂直对齐方式指定为居中
				for (int i = 0; i < 5; i++) {
					Label labelStr1 = new Label(i, 0, Constants.biaotou[i],
							wcfF);
					ws.addCell(labelStr1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		workbook.write();
		workbook.close();
	}

	/**
	 * 写入测试结果
	 * 
	 * @param result
	 * @param fileName
	 * @throws IOException
	 * @throws BiffException
	 * @throws WriteException
	 */
	public void writeResult(List<TestCaseBean> result, String fileName)
			throws IOException, BiffException, WriteException {
		/*
		 * 将测试用例执行情况写入指定文件中
		 */
		this.checkFile(imagePath + c + "_" + fileName);// 检查文件是否存在
		Workbook wb = Workbook.getWorkbook(file);
		// 打开一个文件的副本，并且指定数据写回到原文件
		WritableWorkbook book = Workbook.createWorkbook(file, wb);
		WritableSheet sheet = book.getSheet("sheet1");
		int rows = sheet.getRows();
		// 将内容插入到表中
		for (int i = 0; i < result.size(); i++) {
			sheet.addCell(new Label(0, rows + i, String.valueOf(rows + i)));
			sheet.addCell(new Label(1, rows + i, result.get(i)
					.getPhoneProductName()));
			sheet.addCell(new Label(2, rows + i, result.get(i).getModuleName()));
			sheet.addCell(new Label(3, rows + i, result.get(i).getTestCase()));
			sheet.addCell(new Label(4, rows + i, result.get(i).getResult()));
		}
		book.write();
		book.close();
		wb.close();
	}

	/**
	 * 封装测试用例
	 * 
	 * @param phoneProductName
	 * @param moduleName
	 * @param testCase
	 * @param result
	 * @return
	 */
	public List<TestCaseBean> setResultBean(String phoneProductName,
			String moduleName, String testCase, String result) {
		// 将得到的用例转换成ResultBean
		TestCaseBean bean = new TestCaseBean();
		bean.setPhoneProductName(phoneProductName);
		bean.setModuleName(moduleName);
		bean.setTestCase(testCase);
		bean.setResult(result);
		list.add(bean);
		return list;
	}

}
